package net.hn.hnms.biz.plan.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.plan.domain.PlanWashing;
import net.hn.hnms.biz.plan.mapper.PlanWashingMapper;
import net.hn.hnms.biz.plan.request.PlanWashingReq;
import net.hn.hnms.biz.plan.service.IPlanWashingService;
import net.hn.hnms.biz.plan.vo.PlanWashingVO;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import net.hn.hnms.sys.system.api.RemoteUserService;
import net.hn.hnms.sys.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhaoyang
 * 洗选计划管理服务层实现
 * @date 2022-08-01
 */

@Service
@DS("master")
public class PlanWashingServiceImpl extends BaseService<PlanWashing, PlanWashingVO> implements IPlanWashingService {

    private PlanWashingMapper planWashingMapper;
    @Autowired
    private RemoteUserService remoteUserService;
    public PlanWashingServiceImpl(PlanWashingMapper planWashingMapper) {
        this.planWashingMapper = planWashingMapper;
    }

    /**
     * @param planWashing
     * @param pageQuery   查询洗选计划列表
     */
    @Override
    public ResponsePage<PlanWashingVO> selectPageList(PlanWashingReq planWashing, PageQuery pageQuery) {

        Page<PlanWashing> page = planWashingMapper.selectPage(pageQuery.build(), buildQuery(planWashing).orderByDesc(PlanWashing::getWashingPlanCode).orderByDesc(PlanWashing::getCreateTime));

        List<PlanWashingVO> list = page.getRecords().stream().map(o -> convert(o, PlanWashingVO.class,o.getWashingPlanType(),
                "washingPlanStartDate","washingPlanEndDate")).collect(Collectors.toList());
        list.forEach(ii->{
            LoginUser userInfoById = remoteUserService.getUserInfoById(Long.valueOf(ii.getCreateUserId()));
            if (Optional.ofNullable(userInfoById).isPresent()) {
                ii.setCreateUserName(userInfoById.getNickname());
            }

        });
        return new ResponsePage<>(list, page.getTotal());
    }

    /**
     * 构造查询条件
     *
     * @param req
     * @return LambdaQueryWrapper<PlanDevelopment> 查询条件
     */
    private LambdaQueryWrapper<PlanWashing> buildQuery(PlanWashingReq req) {
        LambdaQueryWrapper<PlanWashing> lqw = new LambdaQueryWrapper<PlanWashing>()
                .like(StrUtil.isNotBlank(req.getWashingPlanCode()), PlanWashing::getWashingPlanCode, req.getWashingPlanCode())
                .like(StrUtil.isNotBlank(req.getWashingPlanName()), PlanWashing::getWashingPlanName, req.getWashingPlanName())
//                .eq(StrUtil.isNotBlank(req.getMineCode()), PlanWashing::getMineCode, req.getMineCode())
                .eq(StrUtil.isNotBlank(req.getWashingPlanType()), PlanWashing::getWashingPlanType, req.getWashingPlanType())
                .eq(StrUtil.isNotBlank(req.getStatus()), PlanWashing::getStatus, req.getStatus())
                .and(o->o.eq(req.getMineCode()!=null, PlanWashing::getMineCode, req.getMineCode()).or().eq(req.getCompanyCode()!=null, PlanWashing::getCompanyCode, req.getCompanyCode()));

        return lqw;
    }

    /**
     * @param planWashing 查询掘进计划列表
     */
    @Override
    public List<PlanWashingVO> selectList(PlanWashingReq planWashing) {
        List<PlanWashing> list = planWashingMapper.selectList(buildQuery(planWashing));
        return list.stream().map(o -> convert(o, PlanWashingVO.class,o.getWashingPlanType(),"washingPlanStartDate","washingPlanEndDate")).collect(Collectors.toList());
    }

    /**
     * @param planWashing 新增洗选计划
     */
    @Override
    public int insert(PlanWashingReq planWashing) {

        PlanWashing insertObj = new PlanWashing();
        copyProperties(planWashing, insertObj, planWashing.getWashingPlanType(),"washingPlanStartDate","washingPlanEndDate");
        //自动生成 计划名称 计划编号
        insertObj.setWashingPlanName(generatePlanName(planWashing.getWashingPlanType(),insertObj.getWashingPlanStartDate()));
        insertObj.setWashingPlanCode(generatePlanCode(planWashing.getWashingPlanType(),insertObj.getWashingPlanStartDate()));
        insertObj.setStatus("0");
        QueryWrapper<PlanWashing> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("washing_plan_code", insertObj.getWashingPlanCode());
        if (planWashingMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        return planWashingMapper.insert(insertObj);
    }

    /**
     * @param idList 批量删除
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> idList) {
        planWashingMapper.deleteBatchIds(idList);
    }

    /**
     * @param planWashing 单个修改 按照主键修改信息
     */
    @Override
    public void updateById(PlanWashingReq planWashing) {
        if (StrUtil.isBlank(planWashing.getWashingPlanId())) {
            throw new HuaNengException(Constants.FAIL, "id不能为空");
        }
        PlanWashing updateObj = new PlanWashing();
        copyProperties(planWashing, updateObj, planWashing.getWashingPlanType(),"washingPlanStartDate","washingPlanEndDate");
        updateObj.setWashingPlanName(generatePlanName(planWashing.getWashingPlanType(),updateObj.getWashingPlanStartDate()));
        updateObj.setWashingPlanCode(generatePlanCode(planWashing.getWashingPlanType(),updateObj.getWashingPlanStartDate()));
        QueryWrapper<PlanWashing> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("washing_plan_code", updateObj.getWashingPlanCode());
        queryWrapper.ne("washing_plan_id", updateObj.getWashingPlanId());
        if (planWashingMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        int updateCount = planWashingMapper.updateById(updateObj);
        if (updateCount == 0) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
    }

    /**
     * @param id 按主键id查询详情
     */
    @Override
    public PlanWashingVO selectDetailById(String id) {
        PlanWashing planWashing = planWashingMapper.selectById(id);
        if (planWashing == null) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
        return convertWithUser(planWashing, PlanWashingVO.class);
    }

    /**
     * 启用/禁用
     * @param id 数据id
     * @param status  status: 0:启用 1:禁用
     */
    public void changeStatus(String id, Integer status) {
        if (status == 1 || status == 0) {
            PlanWashing planMining = planWashingMapper.selectById(id);
            if (planMining == null) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            planMining.setStatus(status + "");
            int res = planWashingMapper.updateById(planMining);
            if (res == 0) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            return;
        }
        throw new HuaNengException(Constants.FAIL, "传入的参数错误");
    }
}
